% -*- mode: tex -*-
<% IF paper %>
\enablemode[<% paper %>]
<% END %>
<% IF font %>
\enablemode[<% font %>]
<% END %>
<% IF fontdim %>
\enablemode[<% fontdim %>]
<% END %>


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                STANDARD                                      %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\enabletrackers[fonts.missing]
\definefontfeature[default][default]
                  [protrusion=quality,
                    expansion=quality,
                    script=latn]

% PARATYPE 

\definefontfeature
[ptfeatures]
[mode=node,liga=yes,kern=yes,tlig=yes,trep=yes,
  ccmp=yes,language=dflt,script=cyrl,
  protrusion=quality,
  expansion=quality]

\starttypescript [sans] [paratype]
  \definefontsynonym[PTSans-Regular]          [file:PTS55F]
  \definefontsynonym[PTSans-Bold]             [file:PTS75F]
  \definefontsynonym[PTSans-BoldItalic]       [file:PTS76F]
  \definefontsynonym[PTSans-Italic]           [file:PTS56F]
\stoptypescript

\starttypescript [serif] [paratype]
  \definefontsynonym[PTSerif-Regular]         [file:PTF55F] 
  \definefontsynonym[PTSerif-Bold]            [file:PTF75F] 
  \definefontsynonym[PTSerif-BoldItalic]      [file:PTF76F] 
  \definefontsynonym[PTSerif-Italic]          [file:PTF56F] 
\stoptypescript

\starttypescript [sans] [paratype] [name]
  \definefontsynonym [Sans]           [PTSans-Regular]     [features=ptfeatures]
  \definefontsynonym [SansItalic]     [PTSans-Italic]      [features=ptfeatures]
  \definefontsynonym [SansSlanted]    [PTSans-Italic]      [features=ptfeatures]
  \definefontsynonym [SansBold]       [PTSans-Bold]        [features=ptfeatures]
  \definefontsynonym [SansBoldItalic] [PTSans-BoldItalic]  [features=ptfeatures]
  \definefontsynonym [SansBoldSlanted][PTSans-BoldItalic]  [features=ptfeatures]
  \definefontsynonym [SansCaps]       [PTSans-Regular]     [features=ptfeatures]
\stoptypescript

\starttypescript [serif] [paratype] [name]
  \definefontsynonym [Serif]           [PTSerif-Regular]     [features=ptfeatures]
  \definefontsynonym [SerifItalic]     [PTSerif-Italic]      [features=ptfeatures]
  \definefontsynonym [SerifSlanted]    [PTSerif-Italic]      [features=ptfeatures]
  \definefontsynonym [SerifBold]       [PTSerif-Bold]        [features=ptfeatures]
  \definefontsynonym [SerifBoldItalic] [PTSerif-BoldItalic]  [features=ptfeatures]
  \definefontsynonym [SerifBoldSlanted][PTSerif-BoldItalic]  [features=ptfeatures]
  \definefontsynonym [SerifCaps]       [PTSerif-Regular]     [features=ptfeatures]
\stoptypescript

\starttypescript [paratype]
  \definetypeface [paratype] [rm] [serif] [paratype] [default]
  \definetypeface [paratype] [ss] [sans]  [paratype]  [default]
  \definetypeface [paratype] [tt] [mono]  [default]   [default]
\stoptypescript

\setupalign[hz,hanging]
\setuptolerance[tolerant]
\setbreakpoints[compound]
\setupindenting[yes,1em]
\setupfootnotes[way=bychapter,align={hz,hanging}]
\setupbodyfont[paratype,11pt]
\setupcaptions[width=\textwidth]

\setupbodyfontenvironment[default][em=italic]

<% IF imposed %>
\setuppagenumbering[alternative=doublesided,location={footer,middle}]
<% ELSE %>
\setuppagenumbering[alternative=singlesided,location={footer,middle}]
<% END %>

\setupcaptions[width=fit,align={hz,hanging}]

\setupheads[%
  sectionnumber=no,number=no,
  align=flushleft,
  align={flushleft,nothyphenated,verytolerant,stretch},
  indentnext=yes,
  tolerance=verytolerant]

\definehead[awikipart][chapter]

\setuphead[awikipart]
          [%
            number=no,
            footer=empty,
            style=\bfd,
            before={\blank[force,2*big]},
            align={middle,nothyphenated,verytolerant,stretch},
            after={\page[yes]}
          ]

% <h3>
\setuphead[chapter]
          [style=\bfc]

\setuphead[title]
          [style=\bfc]


% <h4>
\setuphead[section]
          [style=\bfb]

% <h5>
\setuphead[subsection]
          [style=\bfa]

% <h6>
\setuphead[subsubsection]
          [style=bold]


\setuplist[awikipart]
          [alternative=b,
            interaction=all,
            width=0mm,
            distance=0mm,
            before={\blank[medium]},
            after={\blank[small]},
            style=\bfa,
            criterium=all]
\setuplist[chapter]
          [alternative=c,
            interaction=all,
            width=1mm,
            before={\blank[small]},
            style=bold,
            criterium=all]
\setuplist[section]
          [alternative=c,
            interaction=all,
            width=1mm,
            style=\tf,
            criterium=all]
\setuplist[subsection]
          [alternative=c,
            interaction=all,
            width=8mm,
            distance=0mm,
            style=\tf,
            criterium=all]
\setuplist[subsubsection]
          [alternative=c,
            interaction=all,
            width=15mm,
            style=\tf,
            criterium=all]

\definestartstop
  [awikicenter]
  [before={\blank[line]\startalignment[middle]},
   after={\stopalignment\blank[line]}]

% <right>

\definestartstop
  [awikiright]
  [before={\blank[line]\startalignment[flushright]},
   after={\stopalignment\blank[line]}]

% <blockquote>

\definestartstop
  [blockquote]
  [before={\blank[big]
    \setupnarrower[middle=1em]
    \startnarrower
    \setupindenting[no]
    \setupwhitespace[medium]},
  after={\stopnarrower
    \blank[big]}]

% verse

\definestartstop
  [awikiverse]
  [before={\blank[big]
      \setupnarrower[middle=2em]
      \startnarrower
      \startlines},
    after={\stoplines
      \stopnarrower
      \blank[big]}]

\definestartstop
  [awikibiblio]
  [before={%
      \blank[big]
      \setupnarrower[left=1em]
      \startnarrower[left]
        \setupindenting[yes,-1em,first]},
    after={\stopnarrower
      \blank[big]}]
                
% same as above, but with no spacing around
\definestartstop
  [awikiplay]
  [before={%
      \setupnarrower[left=1em]
      \startnarrower[left]
        \setupindenting[yes,-1em,first]},
    after={\stopnarrower}]



% interaction

<% UNLESS imposed %>
\setupinteraction[state=start,color=black,contrastcolor=black,style=bold]
\placebookmarks[awikipart,chapter,section,subsection,subsubsection][force=yes]
\setupinteractionscreen[option=bookmark]
<% END %>


\setupexternalfigures[%
  maxwidth=\textwidth,
  maxheight=\textheight,
  factor=fit]

\setupitemgroup[itemize][each][packed][indenting=no]

\definemakeup[titlepage][pagestate=start,doublesided=yes]

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                                IMPOSER                                       %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\startusercode

function optimize_signature(pages,min,max)
   local minsignature = min or 40
   local maxsignature = max or 80
   local originalpages = pages

   -- here we want to be sure that the max and min are actual *4
   if (minsignature%4) ~= 0 then
      global.texio.write_nl('term and log', "The minsig you provided is not a multiple of 4, rounding up")
      minsignature = minsignature + (4 - (minsignature % 4))
   end
   if (maxsignature%4) ~= 0 then
      global.texio.write_nl('term and log', "The maxsig you provided is not a multiple of 4, rounding up")
      maxsignature = maxsignature + (4 - (maxsignature % 4))
   end
   global.assert((minsignature % 4) == 0, "I suppose something is wrong, not a n*4")
   global.assert((maxsignature % 4) == 0, "I suppose something is wrong, not a n*4")

   --set needed pages to and and signature to 0
   local neededpages, signature = 0,0

   -- this means that we have to work with n*4, if not, add them to
   -- needed pages 
   local modulo = pages % 4
   if modulo==0 then
      signature=pages
   else
      neededpages = 4 - modulo
   end

   -- add the needed pages to pages
   pages = pages + neededpages
   
   if ((minsignature == 0) or (maxsignature == 0)) then 
      signature = pages -- the whole text
   else
      -- give a try with the signature
      signature = find_signature(pages, maxsignature)
      
      -- if the pages, are more than the max signature, find the right one
      if pages>maxsignature then
	 while signature<minsignature do
	    pages = pages + 4
	    neededpages = 4 + neededpages
	    signature = find_signature(pages, maxsignature)
	    --         global.texio.write_nl('term and log', "Trying signature of " .. signature)
	 end
      end
      global.texio.write_nl('term and log', "Parameters:: maxsignature=" .. maxsignature ..
		   " minsignature=" .. minsignature)
   end
   global.texio.write_nl('term and log', "ImposerMessage:: Original pages: " .. originalpages .. "; " .. 
	 "Signature is " .. signature .. ", " ..
	 neededpages .. " pages are needed, " .. 
	 pages ..  " of output")
   -- let's do it
   tex.print("\\dorecurse{" .. neededpages .. "}{\\page[empty]}")

end

function find_signature(number, maxsignature)
   global.assert(number>3, "I can't find the signature for" .. number .. "pages")
   global.assert((number % 4) == 0, "I suppose something is wrong, not a n*4")
   local i = maxsignature
   while i>0 do
      -- global.texio.write_nl('term and log', "Trying " .. i  .. "for max of " .. maxsignature)
      if (number % i) == 0 then
	 return i
      end
      i = i - 4
   end
end

\stopusercode



\define[1]\fillthesignature{
  \usercode{optimize_signature(#1, <% minsig %>, <% maxsig %>)}}


\define\alibraryflushpages{
  \page[yes] % reset the page
  \fillthesignature{\the\realpageno}
  \page[blank]
}


% various papers 
\definepapersize[halfletter][width=5.5in,height=8.5in]
\definepapersize[halfafour][width=148.5mm,height=210mm]
\definepapersize[quarterletter][width=4.25in,height=5.5in]
\definepapersize[halfafive][width=105mm,height=148mm]
\definepapersize[ereadersixinch][width=88mm,height=110mm]

\startmode[libertine]
  \usetypescript[libertine]
  \setupbodyfont[libertine]
\stopmode

\startmode[pagella]
  \setupbodyfont[pagella]
\stopmode

\startmode[antykwa]
  \setupbodyfont[antykwa-poltawskiego]
\stopmode

\startmode[iwona]
  \setupbodyfont[iwona-medium]
\stopmode

\startmode[helvetica]
  \setupbodyfont[heros]
\stopmode

\startmode[century]
  \setupbodyfont[schola]
\stopmode

\startmode[modern]
  \setupbodyfont[modern]
\stopmode

\startmode[charis]
  \setupbodyfont[charis]
\stopmode        

% override eventual selection

\startmode[twelvept]
  \setupbodyfont[12pt]
\stopmode

\startmode[elevenpt]
  \setupbodyfont[11pt]
\stopmode

\startmode[tenpt]
  \setupbodyfont[10pt]
\stopmode

\startmode[mini]
  \setuppapersize[ereadersixinch][ereadersixinch] % 88mmx110mm
  \setuplayout[%
    backspace=3mm,
    topspace=3mm,
    height=104mm,
    footer=20pt, %
    header=0pt, % no header
    width=82mm] % 10.5 x 11
  \setuptolerance[verytolerant,stretch]
\stopmode

% for the plain A4 and letter, we use the classic LaTeX dimensions
% from the article class
\startmode[a4]
  \setuppapersize[A4][A4]
  \setuplayout[%
    backspace=42mm,
    topspace=45mm,
    height=218mm,
    footer=10mm,
    header=0pt, % no header
    width=126mm]
\stopmode

\startmode[letter]
  \setuppapersize[letter][letter]
  \setuplayout[%
    backspace=44mm,
    topspace=46mm,
    height=199mm,
    footer=10mm,
    header=0pt, % no header
    width=126mm]
\stopmode


% A4 imposed (A5), with no bc

\startmode[a4imposed]
% DIV=15 148 × 210: these are meant not to have binding correction,
  % but just to play safe, let's say 1mm => 147x210
  \setuppapersize[halfafour][halfafour]
  \setuplayout[%
    backspace=10.8mm, % 146/15 = 9.8 + 1
    topspace=14mm, % 210/15 =  14
    height=182mm, % 14 x 12 + 14 of the footer
    footer=14mm, %
    header=0pt, % no header
    width=117.6mm] % 9.8 x 12
\stopmode

% A4 imposed (A5), with bc
\startmode[a4imposedbc]
  \setuppapersize[halfafour][halfafour]
  \setuplayout[% 14 mm was a bit too near to the spine, using the glue binding
    backspace=17.3mm,  % 140/15 + 8 =
    topspace=14mm, % 210/15 =  14
    height=182mm, % 14 x 12 + 14 of the footer
    footer=14mm, %
    header=0pt, % no header
    width=112mm] % 9.333 x 12
\stopmode


\startmode[letterimposedbc] % 139.7mm x 215.9 mm
  \setuppapersize[halfletter][halfletter]
  % DIV=15 8mm binding corr, => 132 x 216
  \setuplayout[%
    backspace=16.8mm, % 8.8 + 8
    topspace=14.4mm, % 216/15 =  14.4
    height=187.2mm, % 15.4 x 11 + 15 of the footer
    footer=14.4mm, %
    header=0pt, % no header
    width=105.6mm] % 8.8 x 12
\stopmode

\startmode[letterimposed] % 139.7mm x 215.9 mm
  \setuppapersize[halfletter][halfletter]
  % DIV=15, 1mm binding correction. => 138.7x215.9
  \setuplayout[%
    backspace=10.3mm, % 9.24 + 1
    topspace=14.4mm, % 216/15 =  14.4
    height=187.2mm, % 15.4 x 11 + 15 of the footer
    footer=14.4mm, %
    header=0pt, % no header
    width=111mm] % 9.24 x 12
\stopmode

%%% new formats for mini books
%%% \definepapersize[halfafive][width=105mm,height=148mm]

\startmode[a5imposed]
% DIV=12 105x148 : these are meant not to have binding correction,
  % but just to play safe, let's say 1mm => 104x148
  \setuppapersize[halfafive][halfafive]
  \setuplayout[%
    backspace=9.6mm,
    topspace=12.3mm,
    height=123.5mm, % 14 x 12 + 14 of the footer
    footer=12.3mm, %
    header=0pt, % no header
    width=78.8mm] % 9.8 x 12
\stopmode

% A5 imposed (A6), with bc
\startmode[a5imposedbc]
% DIV=12 105x148 : with binding correction,
  % let's say 8mm => 96x148
  \setuppapersize[halfafive][halfafive]
  \setuplayout[%
    backspace=16mm,
    topspace=12.3mm,
    height=123.5mm, % 14 x 12 + 14 of the footer
    footer=12.3mm, %
    header=0pt, % no header
    width=72mm] % 9.8 x 12
\stopmode

%%% \definepapersize[quarterletter][width=4.25in,height=5.5in]

% DIV=12 width=4.25in (108mm),height=5.5in (140mm) 
\startmode[halfletterimposed] % 107x140
  \setuppapersize[quarterletter][quarterletter]
  \setuplayout[%
    backspace=10mm,
    topspace=11.6mm,
    height=116mm,
    footer=11.6mm,
    header=0pt, % no header
    width=80mm] % 9.24 x 12
\stopmode

\startmode[halfletterimposedbc]
  \setuppapersize[quarterletter][quarterletter]
  \setuplayout[%
    backspace=15.4mm,
    topspace=11.6mm,
    height=116mm,
    footer=11.6mm,
    header=0pt, % no header
    width=76mm] % 9.24 x 12
\stopmode

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%                            DOCUMENT BEGINS                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\mainlanguage[ru]

\starttext

<% IF tocwanted %>

\placelist[awikipart,chapter,section,subsection]

\page[yes]

<% END %>



